﻿using AutoMapper;
using HelenServer.UserCenter.Dal;
using IdentityModel;
using IdentityServer4.Models;
using IdentityServer4.Validation;
using Microsoft.EntityFrameworkCore;

namespace HelenServer.UserCenter.Authentication;

internal class UserValidator : IResourceOwnerPasswordValidator
{
    private readonly UserCenterDbContext _context;
    private readonly IMapper _mapper;

    public UserValidator(UserCenterDbContext context, IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
    }

    public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
    {
        try
        {
            var user = await _context.Users.FirstOrDefaultAsync(n => n.Email == context.UserName);

            if (user is not null && Helen.Validate(user.Password!, context.Password))
            {
                var idUser = _mapper.Map<User, IdentityUser>(user);
                context.Result = new GrantValidationResult(
                    idUser.SubjectId ?? throw new ArgumentException("Subject ID not set", nameof(idUser.SubjectId)),
                    OidcConstants.AuthenticationMethods.Password,
                    idUser.Claims);
            }
            else
            {
                context.Result = new GrantValidationResult(
                    TokenRequestErrors.InvalidGrant, "Incorrect username or password.");
            }
        }
        catch
        { }
    }
}
